const { ccclass, property, playOnFocus, executeInEditMode } = cc._decorator;
import { menu } from '../../../app/decorator';

@ccclass
@playOnFocus
@executeInEditMode
@menu(__filename, '环形布局')
export default class LayoutCircle extends cc.Component {
    @property
    private _radius: number = 100;
    @property
    get radius() { return this._radius; }
    set radius(num: number) {
        this._radius = num;
        this.refreshView();
    }

    @property
    _offset: number = 0;
    @property({ range: [-180, 180], tooltip: '偏移' })
    get offset() {
        return this._offset;
    }
    set offset(vaulue) {
        this._offset = vaulue;
        this.refreshView();
    }

    private readyRefresh = false;

    protected onLoad() {
        this.refreshView();
    }

    protected onEnable() {
        this.node.on(cc.Node.EventType.CHILD_ADDED, this.refreshView, this);
        this.node.on(cc.Node.EventType.CHILD_REMOVED, this.refreshView, this);
    }

    protected onDisable() {
        this.node.off(cc.Node.EventType.CHILD_ADDED, this.refreshView, this);
    }

    refreshView() {
        this.readyRefresh = true;
    }

    private _refreshView() {
        this.readyRefresh = false;
        const children = this.node.children;
        const count = children.length;
        const angle = Math.PI / count * 2;
        const offset = this.offset / 360 * Math.PI * 2;

        for (let index = 0, _angle = 0; index < count; index++) {
            const node = children[index];
            _angle = angle * index + offset;

            node.x = this.radius * Math.cos(_angle);
            node.y = this.radius * Math.sin(_angle);

            node.angle = -(90 - _angle / Math.PI * 180);
        }
    }

    update() {
        if (this.readyRefresh === false) return;
        this._refreshView();
    }
}
